﻿using DataAccess.Models;

using Solr;
using Solr.Commons;
using Solr.Impl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DataAccess.Solr
{
    public class SolrProductBLL
    {
        static ISolrResponseParser<NamedList, ResponseHeader> binaryResponseHeaderParser = new BinaryResponseHeaderParser();
        static IObjectDeserializer<ProductListModel> exampleDeserializer = new ProductDeserializer();
        static ISolrResponseParser<NamedList, QueryResults<ProductListModel>> binaryQueryResultsParser = new BinaryQueryResultsParser<ProductListModel>(exampleDeserializer);

        static ISolrResponseParser<NamedList, IList<GroupQueryResults<ProductListModel>>> GroupByeParser = new BinaryGroupQueryResultsParser<ProductListModel>(exampleDeserializer);

        static ISolrQueryConnection<NamedList> Productconnection = null;
        static ISolrQueryOperations<NamedList> Productoperations = null;
        static ISolrResponseParser<NamedList, IDictionary<string, IDictionary<string, IList<string>>>> binaryHighlightingParser = new BinaryHighlightingParser();
        private static string SolrPath = System.Configuration.ConfigurationManager.AppSettings["Solr"];
        static string ProductCollectionName = "product";
        public SolrProductBLL()
        {

        }
        static SolrProductBLL()
        {
            if (Productconnection == null && Productoperations == null)
            {

                Productconnection = new SolrQueryConnection<NamedList>() { ServerUrl = SolrPath };
                Productoperations = new SolrQueryOperations<NamedList>(Productconnection) { ResponseWriter = "javabin" };
            }

        }
        /// <summary>
        /// SolrQuestion反序列化器
        /// </summary>
        public class ProductDeserializer : IObjectDeserializer<ProductListModel>
        {
            public IEnumerable<ProductListModel> Deserialize(SolrDocumentList result)
            {
                foreach (SolrDocument doc in result)
                {
                    yield return new ProductListModel()
                    {

                        auctionId = doc["id"] != null ? long.Parse(doc["id"].ToString()) : 0,
                        //auctionUrl = doc["auctionUrl"] != null ? doc["auctionUrl"].ToString() : "",
                        biz30day = doc["biz30day"] != null ? int.Parse(doc["biz30day"].ToString()) : 0,
                       // Introduce = doc["Introduce"] != null ? doc["Introduce"].ToString() : "",
                        couponAmount = doc["couponAmount"] != null ? float.Parse(doc["couponAmount"].ToString()) : 0,
                        
                        pictUrl = doc["pictUrl"] != null ? doc["pictUrl"].ToString() + "_480x480" : "",
                        zkPrice = doc["zkPrice"] != null ? float.Parse(doc["zkPrice"].ToString()) : 0,
                        tkRate = doc["tkRate"] != null ? (decimal.Parse(doc["tkRate"].ToString())).ToString("F2") : "0",
                        //最终商品价格
                        Price = doc["zkPrice"] != null ? (decimal.Parse(doc["zkPrice"].ToString()) - decimal.Parse(doc["couponAmount"].ToString())).ToString("F2") : "0",
                        userType = doc["userType"] != null ? doc["userType"].ToString() : "0",
                        shopTitle = !string.IsNullOrEmpty(doc["shopTitle"].ToString()) ? doc["shopTitle"].ToString() : (int.Parse(doc["DataTypeID"].ToString()) == 0 ? "淘宝商品" : "天猫商品"),
                        DataTypeID = doc["DataTypeID"] != null ? int.Parse(doc["DataTypeID"].ToString()) : 0,
                        title = doc["productname"] != null ? doc["productname"].ToString() : "",

                    };
                }
            }
        }
        /// <summary>
        /// 通过商品ID查询
        /// </summary>
        /// <param name="ProductSpecRelRid"></param>
        /// <returns></returns>
        public ProductListModel GetProductListModelByProductSpecRelRid(int auctionId)
        {
            ISolrQuery query = new SolrQuery("id:" + auctionId + "");

            var options = new Dictionary<string, ICollection<string>>();

            options.Add("start", new string[] { "0" });
            options.Add("rows", new string[] { "1" });

            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);

            var examples = binaryQueryResultsParser.Parse(result);

            return examples.FirstOrDefault();
        }

        /// <summary>
        /// 根据查询条件查询
        /// </summary>
        /// <param name="Condition"></param>
        /// <returns></returns>
        public ProductListModel GetProductListModelByCondition(string Condition)
        {
            ISolrQuery query = new SolrQuery(Condition);

            var options = new Dictionary<string, ICollection<string>>();

            options.Add("start", new string[] { "0" });
            options.Add("rows", new string[] { "1" });

            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);

            var examples = binaryQueryResultsParser.Parse(result);

            return examples.FirstOrDefault();
        }




        public PagingList<ProductListModel> GetProductListModelPage(string strWhere, int PageIndex, int PageSize)
        {
            ISolrQuery query = new SolrQuery(strWhere);

            var options = new Dictionary<string, ICollection<string>>();
            int Count = 0;
            options.Add("start", new string[] { PageIndex.ToString() });
            options.Add("rows", new string[] { PageSize.ToString() });
            options.Add("sort", new string[] { "id desc" });
            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
            var solrDocumentList = (SolrDocumentList)result.Get("response");
            if (solrDocumentList != null)
            {
                Count = (int)solrDocumentList.NumFound;
            }
            var examples = binaryQueryResultsParser.Parse(result);
            PagingList<ProductListModel> list = new PagingList<ProductListModel>();
            list.CurrentPageList = examples.ToList();
            list.Total = Count;
            return list;
        }

        public PagingList<ProductListModel> GetProductListModelPage(string strWhere, int startIndex, int PageSize, string sort)
        {
            int Count = 0;
            ISolrQuery query = new SolrQuery(strWhere);
            var options = new Dictionary<string, ICollection<string>>();
            options.Add("start", new string[] { startIndex.ToString() });
            options.Add("rows", new string[] { PageSize.ToString() });
            options.Add("sort", new string[] { sort });
            if (strWhere.Contains("productname"))
            {
                options.Add("hl", new string[] { "true" });
                options.Add("hl.fl", new string[] { "productname" });
                options.Add("hl.simple.pre", new string[] { "<font style=\"color:#FF0000\">" });
                options.Add("hl.simple.post", new string[] { "</font>" });
            }
            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
            var solrDocumentList = (SolrDocumentList)result.Get("response");
            if (solrDocumentList != null)
            {
                Count = (int)solrDocumentList.NumFound;
            }
            var examples = binaryQueryResultsParser.Parse(result);
            PagingList<ProductListModel> pagelist = new PagingList<ProductListModel>();

            pagelist.Total = Count;
            if (strWhere.Contains("productname"))
            {
                var highlights = binaryHighlightingParser.Parse(result);
                var list = examples.ToList();
                foreach (var item in list)
                {
                    KeyValuePair<string, IDictionary<string, IList<string>>> dictionary = highlights.First(p => p.Key == item.auctionId.ToString());
                    Dictionary<string, IList<string>> values1 = (Dictionary<string, IList<string>>)dictionary.Value;
                    Dictionary<string, IList<string>>.ValueCollection values2 = (Dictionary<string, IList<string>>.ValueCollection)values1.Values;
                    for (int i = 0; i < values1.ToList().Count; i++)
                    {
                        if (values1.ToList()[i].Key == "productname")
                        {
                            item.title = values2.ToList()[i].ToList()[0];
                            continue;
                        }
                    }
                }
                pagelist.CurrentPageList = list;
                return pagelist;
            }

            pagelist.CurrentPageList = examples.ToList();
            return pagelist;
        }


        /// <summary>
        /// 分组查询
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="PageSize"></param>
        /// <param name="sort"></param>
        /// <returns></returns>
        public List<ProductListModel> GetGroupByProductList(string strWhere, int PageSize, string sort)
        {
            ISolrQuery query = new SolrQuery(strWhere);
            var options = new Dictionary<string, ICollection<string>>();
            options.Add("group", new string[] { "true" });
            options.Add("group.field", new string[] { "SkuImgUrl" });
            options.Add("group.limit", new string[] { PageSize.ToString() });
            options.Add("sort", new string[] { sort });
            options.Add("start", new string[] { "0" });
            options.Add("rows", new string[] { "9" });
            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
            List<ProductListModel> list = new List<ProductListModel>();
            IList<GroupQueryResults<ProductListModel>> group = GroupByeParser.Parse(result);
            foreach (var item in group)
            {

                foreach (var em in item.Groups.ToList())
                {
                    list.AddRange(em.QueryResults.ToList());
                }
            }
            return list;
        }

        /// <summary>
        /// 搜索商品
        /// </summary>
        /// <param name="strWhere"></param>
        /// <param name="startIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="sort"></param>
        /// <param name="Count"></param>
        /// <returns></returns>
        public List<ProductListModel> SearchProductListPage(string strWhere, int startIndex, int PageSize, string sort, ref int Count)
        {
            ISolrQuery query = new SolrQuery(strWhere);
            var options = new Dictionary<string, ICollection<string>>();
            options.Add("start", new string[] { startIndex.ToString() });
            options.Add("rows", new string[] { PageSize.ToString() });
            options.Add("sort", new string[] { sort });
            options.Add("hl", new string[] { "true" });
            options.Add("hl.fl", new string[] { "productname" });
            options.Add("hl.simple.pre", new string[] { "<font style=\"color:#FF0000\">" });
            options.Add("hl.simple.post", new string[] { "</font>" });
            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
            var solrDocumentList = (SolrDocumentList)result.Get("response");
            if (solrDocumentList != null)
            {
                Count = (int)solrDocumentList.NumFound;
            }
            var examples = binaryQueryResultsParser.Parse(result);
            var highlights = binaryHighlightingParser.Parse(result);
            // return examples.ToList();
            var list = examples.ToList();
            foreach (var item in list)
            {
                KeyValuePair<string, IDictionary<string, IList<string>>> dictionary = highlights.First(p => p.Key == item.auctionId.ToString());
                Dictionary<string, IList<string>> values1 = (Dictionary<string, IList<string>>)dictionary.Value;
                Dictionary<string, IList<string>>.ValueCollection values2 = (Dictionary<string, IList<string>>.ValueCollection)values1.Values;
                for (int i = 0; i < values1.ToList().Count; i++)
                {
                    if (values1.ToList()[i].Key == "productname")
                    {
                        item.title = values2.ToList()[i].ToList()[0];
                        continue;
                    }
                }
            }
            return list;
        }

        /// <summary>
        /// 随机获取商品
        /// </summary>
        /// <param name="size">返回商品条数</param>
        /// <returns></returns>
        public List<ProductListModel> GetProductRandom(int size)
        {
            ISolrQuery query = new SolrQuery("*:*");

            var options = new Dictionary<string, ICollection<string>>();

            options.Add("start", new string[] { "0" });
            options.Add("rows", new string[] { size.ToString() });

            int r = new Random().Next(0, 10000);
            options.Add("sort", new string[] { "random_" + r.ToString() + " desc" });
            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
            var examples = binaryQueryResultsParser.Parse(result);
            return examples.ToList();
        }


        public List<ProductClass> GetProductClass()
        {
            ISolrQuery query = new SolrQuery("*:*");

            var options = new Dictionary<string, ICollection<string>>();
            options.Add("facet", new string[] { "on" });
            options.Add("facet.field", new string[] { "DataTypeID" });
            var result = Productoperations.Query(ProductCollectionName, "/select", query, options);
            var solrDocumentList = (SolrDocumentList)result.Get("response");
            var header = binaryResponseHeaderParser.Parse(result);
            var examples = binaryQueryResultsParser.Parse(result);
            var de = new BinaryFacetQueriesParser().Parse(result);

            IDictionary<string, IList<FacetField>> facetDic = new BinaryFacetFieldsParser().Parse(result);
            List<ProductClass> list = ProductClassList.ClassList;
            foreach (var item in facetDic)
            {

                foreach (var facetItem in item.Value)
                {
                    var m = list.Find(c => c.ID == int.Parse(facetItem.Name));
                    if (m != null)
                    {
                        list.Remove(m);
                        list.Add(new ProductClass { ID = m.ID, Name = m.Name, Count = facetItem.Count });

                    }
                }
            }

            return list.OrderBy(c => c.ID).ToList();
        }

    }
}
